package lc.oa.ui.fragment;


import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.viewpager.widget.ViewPager;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.android.volley.toolbox.Volley;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;

import org.json.JSONObject;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import lc.oa.BuildConfig;
import lc.oa.R;
import lc.oa.data.model.Department;
import lc.oa.data.model.LoggedInUser;
import lc.oa.enums.HttpStatus;
import lc.oa.net.http.HttpQueueHelper;
import lc.oa.net.http.request.GsonRequest;
import lc.oa.model.RResult;
import lc.oa.net.ws.OAWebSocketListener;
import lc.oa.net.ws.WebSocketHandler;
import lc.oa.ui.adapter.SpinAdapter;
import lc.oa.ui.base.BaseFragment;
import lombok.SneakyThrows;
import okhttp3.WebSocket;
import okio.ByteString;

/**
 * @Description: 业绩主页
 * @Author: lucifer
 * @CreateDate: 2020/8/7 14:01
 * @UpdateUser:
 * @UpdateDate:
 * @UpdateRemark:
 * @Version: 1.0
 */
public class AchievementFragment extends BaseFragment implements ViewPager.OnPageChangeListener {
    TextView tvException;
    private PieChart chart;

    protected Typeface tfRegular;
    protected Typeface tfLight;
    protected final String[] months = new String[] {
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"
    };

    protected final String[] parties = new String[] {
            "利润完成比", "回款率", "发票回收率"
    };
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_achievement, container, false);
        tfRegular = Typeface.createFromAsset(getActivity().getAssets(), "OpenSans-Regular.ttf");
        tfLight = Typeface.createFromAsset(getActivity().getAssets(), "OpenSans-Light.ttf");
        initData(view);
        bindChart(view);

       // tvException = view.findViewById(R.id.tvResponseResult);

//        bindEventHandler(view);
//        bindWebsocketHandler(view);
        return view;
    }
    private Spinner spinner;
     /**
      * @method  初始化部门及日期统计条件
      * @description
      * @date: 2020/8/13 12:53
      * @author: lucifer
      * @param 
      * @return 
      */
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initData(View view) {
        spinner=view.findViewById(R.id.spDepartements);
        //List<? extends Map<String, ?>>  data=new ArrayList<>();
        //data.add(new HashMap<>());
//        data.add("2","部门2");
        List<Department> departmentList=new ArrayList<>();
        departmentList.add(new Department("1","部门1"));
        departmentList.add(new Department("2","部门2"));
       // Department[] depsValues=  departmentList.toArray(new Department[0]);
//       String[] deps=new String[]{"部门1","部门2"}; //= (String[]) departmentList.stream().map(f->f.getDepName()).toArray();
        SpinAdapter<Department> spinAdapter=new SpinAdapter<Department>(getContext(),R.layout.spinner,departmentList,null);//"depName");
        spinner.setAdapter(spinAdapter);

        //内置写法
      //  ArrayAdapter<Department> adapter = new ArrayAdapter<Department>(this.getContext(),R.layout.support_simple_spinner_dropdown_item,departmentList);
     //   spinner.setAdapter(adapter);
        //spinner.setBackgroundColor(0x0);
       // spinAdapter.setDropDownViewResource(R.layout.spinner);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Department user = (Department) parent.getSelectedItem();
                Log.d("数据","选中了-->"+user.toString());
              // int pos =spinAdapter.getPosition(user);

              // spinner.setSelection(0,true);
              //  spinAdapter.setSelectedPostion(position);
                //spinner.set
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


    private void moveOffScreen() {

        DisplayMetrics displayMetrics = new DisplayMetrics();
       this.getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        int height = displayMetrics.heightPixels;

        int offset = (int)(height * 0.65); /* percent to move */

        RelativeLayout.LayoutParams rlParams =
                (RelativeLayout.LayoutParams) chart.getLayoutParams();
       // rlParams.setMargins(0, 0, 0, -offset);
        chart.setLayoutParams(rlParams);
    }

    private SpannableString generateCenterSpannableText() {

        SpannableString s = new SpannableString("MPAndroidChart\ndeveloped by Philipp Jahoda");
        s.setSpan(new RelativeSizeSpan(1.7f), 0, 14, 0);
        s.setSpan(new StyleSpan(Typeface.NORMAL), 14, s.length() - 15, 0);
        s.setSpan(new ForegroundColorSpan(Color.GRAY), 14, s.length() - 15, 0);
        s.setSpan(new RelativeSizeSpan(.8f), 14, s.length() - 15, 0);
        s.setSpan(new StyleSpan(Typeface.ITALIC), s.length() - 14, s.length(), 0);
        s.setSpan(new ForegroundColorSpan(ColorTemplate.getHoloBlue()), s.length() - 14, s.length(), 0);
        return s;
    }
    private void bindChart(View view) {

        chart = view.findViewById(R.id.chart1);
        chart.setBackgroundColor(Color.WHITE);

        //moveOffScreen();

        chart.setUsePercentValues(true);
        chart.getDescription().setEnabled(false);

        chart.setCenterTextTypeface(tfLight);
        chart.setCenterText(generateCenterSpannableText());

        chart.setDrawHoleEnabled(true);
        chart.setHoleColor(Color.WHITE);

        chart.setTransparentCircleColor(Color.WHITE);
        chart.setTransparentCircleAlpha(110);

        chart.setHoleRadius(58f);
        chart.setTransparentCircleRadius(61f);

        chart.setDrawCenterText(true);

        chart.setRotationEnabled(false);
        chart.setHighlightPerTapEnabled(true);

       // chart.setMaxAngle(180f); // HALF CHART
      //  chart.setRotationAngle(180f);
        chart.setCenterTextOffset(0, -20);

        setData(3, 100);

        chart.animateY(1400, Easing.EaseInOutQuad);

        Legend l = chart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setXEntrySpace(7f);
        l.setYEntrySpace(0f);
        l.setYOffset(0f);

        // entry label styling
        chart.setEntryLabelColor(Color.WHITE);
        chart.setEntryLabelTypeface(tfRegular);
        chart.setEntryLabelTextSize(12f);
    }
    private void setData(int count, float range) {

        ArrayList<PieEntry> values = new ArrayList<>();

        for (int i = 0; i < count; i++) {
            values.add(new PieEntry((float) ((Math.random() * range) + range / 5), parties[i ]));
        }

        PieDataSet dataSet = new PieDataSet(values, "Election Results");
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
        //dataSet.setSelectionShift(0f);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
        data.setValueTypeface(tfLight);
        chart.setData(data);

        chart.invalidate();
    }

    //    private Handler handler2=new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what){
//                case 1:
//                    //UI线程
//                    //textView.setText(msg.obj.toString());
//                    tvException.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm.ssss").format(new Date())
//                            +"--->"+msg.obj);
//                case 2:
//                    //UI线程
//                    //textView.setText(msg.obj.toString());
//                    tvException.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm.ssss").format(new Date())
//                            +"--->"+msg.obj);
//                case 3:
//                    //UI线程
//                    //textView.setText(msg.obj.toString());
//                    tvException.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm.ssss").format(new Date())
//                            +"--->"+msg.obj);
//            }
//        }
//    };
    private void bindWebsocketHandler(View view) {
        Button btnConnectWebsocket = view.findViewById(R.id.btnWebSocket);
        // TextView tvException=view.findViewById(R.id.tvResponseResult);
        OAWebSocketListener listeners = new OAWebSocketListener() {
            @Override
            public void onMessage(WebSocket webSocket, String text) {
                Log.d("onMessage", "onMessage(WebSocket webSocket, String text)");
                //    TextView tvException=view.findViewById(R.id.tvResponseResult);
                // tvException.setText(text);
                //切换到UI线程
                Message message = new Message();
                //区分标志
                message.what = 3;
                //传参到ui线程
                message.obj = text;
                handler.sendMessage(message);
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                Log.d("onMessage", "onMessage(WebSocket webSocket, ByteString bytes)");
                // TextView tvException=view.findViewById(R.id.tvResponseResult);
                // tvException.setText(bytes.string(Charset.defaultCharset()));
                //切换到UI线程
                Message message = new Message();
                //区分标志
                message.what = 2;
                //传参到ui线程
                message.obj = bytes.string(Charset.defaultCharset());
                handler.sendMessage(message);
            }

            @Override
            public void onOpen(WebSocket webSocket, okhttp3.Response response) {
                //TextView tvException=view.findViewById(R.id.tvResponseResult);
//                tvException.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm.ssss").format(new Date())
//                        +"--->"+response);
                //切换到UI线程
                Message message = new Message();
                //区分标志
                message.what = 1;
                //传参到ui线程
                message.obj = response;
                handler.sendMessage(message);
            }
        };
        btnConnectWebsocket.setOnClickListener(new View.OnClickListener() {
            @SneakyThrows
            @Override
            public void onClick(View v) {

                //同步Post请求必须在子线程中执行
                new Thread(new Runnable() {
                    @SneakyThrows
                    @Override
                    public void run() {
                        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
                        String url = BuildConfig.AUTH_API_URL + "/api/v1/Login/Login";
                        RequestFuture<JSONObject> future = RequestFuture.newFuture();
                        // SignData signData = new SignData();
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("loginType", "10");
                        jsonObject.put("signData", "");
                        jsonObject.put("signVal", "");
                        jsonObject.put("userName", "18311329010");
                        jsonObject.put("userPassword", "82273a6ba2126d3af24ce2d0cb0af515");
                        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonObject, future, future);
                        requestQueue.add(request);
                        JSONObject response = null;
                        try {
                            response = future.get(); // this will block
                            if (Integer.parseInt(response.get("code") + "") == HttpStatus.OK.getCode().intValue()) {
                                Log.d("登录信息", "登录成功!");

                                JSONObject data = response.getJSONObject("data");
                                String userId = data.getString("userId");
                                String token = data.getString("tokenMsg");
                                Log.i("Web socket test", "Web socket test");

                                LoggedInUser users = new LoggedInUser();
                                users.setUserId(userId);
                                users.setToken(token);

                                Message message = new Message();
                                //区分标志
                                message.what = -1;
                                //传参到ui线程
                                message.obj = users;
                                handler.sendMessage(message);

                                WebSocketHandler webSocketHandler = WebSocketHandler.getInstance(listeners);
//                String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb3JwSWQiOm51bGwsImNvcnBOYW1lIjpudWxsLCJlbmFibGVkIjowLCJleHBpcmUiOjE1OTc2NTQ0NjcwMjgsImlzVUtleUNoZWNrIjowLCJtb2JpbGUiOiIxODMxMTMyOTAxMCIsInJvbGUiOjAsInRpbWUiOjAsInVzZXJJZCI6ImRmYjA0MWI5MGRiMjQ5NTNiNjA1YjZjN2U2ZjQyYzM1IiwidXNlck5hbWUiOiLlvKDmmZPmnpcifQ.XBn3dVjjkP_QP_jFWHx41PS-9ZC_pCEgZnQcZ59kkJI";
                                webSocketHandler.connect(token);
                            }
                        } catch (InterruptedException e) {
                            // exception handling
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            // exception handling
                            e.printStackTrace();
                        }
//                catch (TimeoutException e) {
//                    e.printStackTrace();
//                }
                        Log.d("响应结果", response.toString());
                    }
                }).start();


//
//                WebSocketHandler webSocketHandler =WebSocketHandler.getInstance(listeners);
//                String token="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb3JwSWQiOm51bGwsImNvcnBOYW1lIjpudWxsLCJlbmFibGVkIjowLCJleHBpcmUiOjE1OTc2NTQ0NjcwMjgsImlzVUtleUNoZWNrIjowLCJtb2JpbGUiOiIxODMxMTMyOTAxMCIsInJvbGUiOjAsInRpbWUiOjAsInVzZXJJZCI6ImRmYjA0MWI5MGRiMjQ5NTNiNjA1YjZjN2U2ZjQyYzM1IiwidXNlck5hbWUiOiLlvKDmmZPmnpcifQ.XBn3dVjjkP_QP_jFWHx41PS-9ZC_pCEgZnQcZ59kkJI";
//                webSocketHandler.connect(token);
            }
        });
    }

    /**
     * @method 绑定事件处理
     * @description 服务交互测试
     * @date: 2020/8/7 14:02
     * @author: lucifer
     */
    private void bindEventHandler(View view) {
        TextView tvResponseResult = view.findViewById(R.id.tvResponseResult);
        Button btnJson = view.findViewById(R.id.buttonJson);
        btnJson.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //   String url="https://oa-dev.lecarlink.com/lc.oa.service/test/test";
                //    String url="http://192.168.1.10:60010/lc.secret.service/test/test2";
                // String url= BuildConfig.API_URL+"/test/test2";
                String url = BuildConfig.API_URL + getString(R.string.test);
                Response.Listener listerSuccess = new Response.Listener() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onResponse(Object response) {
                        Log.e("---------响应日志-------------", "请求成功!");
                        Log.e("---------响应日志-------------", "响应数据-->" + response.toString());
                        tvResponseResult.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm.ssss").format(new Date())
                                + "--->" + response.toString());
                    }
                };
                Response.ErrorListener errLister = new Response.ErrorListener() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.i("---------响应日志-------------", "响应失败!", error);
                        error.printStackTrace();
                    }
                };

//                Map<String, String> header=new HashMap<>();
//                header.put("Content-Type","application/json");
//                header.put("Content-Type","text/html;charset=UTF-8");
//header=null;
                // GsonRequest<RResult> gsonRequest=new GsonRequest<RResult>(url, RResult.class,null,listerSuccess,errLister);
                GsonRequest<RResult> gsonRequest = new GsonRequest<RResult>(url, RResult.class, null, listerSuccess, errLister);
                HttpQueueHelper.getInstance(getContext()).addToRequestQueue(gsonRequest);
            }
        });
        Button btnNonJson = view.findViewById(R.id.buttonNonJson);
        btnNonJson.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "https://oa-dev.lecarlink.com/lc.oa.service/test/test";
                // String url="http://192.168.1.10:60010/lc.secret.service/test/test2";
                Response.Listener listerSuccess = new Response.Listener() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onResponse(Object response) {
                        Log.e("---------响应日志-------------", "请求成功!");
                        Log.e("---------响应日志-------------", "响应数据-->" + response.toString());
                    }
                };
                Response.ErrorListener errLister = new Response.ErrorListener() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.i("---------响应日志-------------", "响应失败!", error);
                        error.printStackTrace();
                    }
                };

//                Map<String, String> header=new HashMap<>();
//                header.put("Content-Type","application/json");
//                header.put("Content-Type","text/html;charset=UTF-8");
//header=null;
                // GsonRequest<RResult> gsonRequest=new GsonRequest<RResult>(url, RResult.class,null,listerSuccess,errLister);
                GsonRequest<String> gsonRequest = new GsonRequest<String>(url, String.class, null, listerSuccess, errLister);
                HttpQueueHelper.getInstance(getContext()).addToRequestQueue(gsonRequest);
            }
        });
        Button btnNonJson2 = view.findViewById(R.id.buttonNonJson2);
        btnNonJson2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = "http://192.168.1.10:60010/lc.secret.service/test/test3";
                // String url="http://192.168.1.10:60010/lc.secret.service/test/test2";
                Response.Listener listerSuccess = new Response.Listener() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onResponse(Object response) {
                        Log.e("---------响应日志-------------", "请求成功!");
                        Log.e("---------响应日志-------------", "响应数据-->" + response.toString());
                    }
                };
                Response.ErrorListener errLister = new Response.ErrorListener() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.i("---------响应日志-------------", "响应失败!", error);
                        error.printStackTrace();
                    }
                };

//                Map<String, String> header=new HashMap<>();
//                header.put("Content-Type","application/json");
//                header.put("Content-Type","text/html;charset=UTF-8");
//header=null;
                // GsonRequest<RResult> gsonRequest=new GsonRequest<RResult>(url, RResult.class,null,listerSuccess,errLister);
                GsonRequest<RResult> gsonRequest = new GsonRequest<RResult>(url, RResult.class, null, listerSuccess, errLister);
                HttpQueueHelper.getInstance(getContext()).addToRequestQueue(gsonRequest);

            }
        });
    }

    //UI线程
    @Override
    protected void handlerMessage1(Message msg) {
        switch (msg.what) {
            case 1:
                //UI线程
                //textView.setText(msg.obj.toString());
                tvException.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm.ssss").format(new Date())
                        + "--->" + msg.obj);
            case 2:
                //UI线程
                //textView.setText(msg.obj.toString());
                tvException.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm.ssss").format(new Date())
                        + "--->" + msg.obj);
            case 3:
                //UI线程
                //textView.setText(msg.obj.toString());
                tvException.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm.ssss").format(new Date())
                        + "--->" + msg.obj);
            case -1:
                Toast.makeText(getContext(),msg.obj.toString(),Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initControl() {

    }

    @Override
    public void onModeChanged(int action, Object... values) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
